<template>
  <div class="order">
    <div class="order-content">
      <el-tabs class="site-tabs" v-model="activeName" @tab-click="onTabClick">
        <el-tab-pane v-for="(tab, index) in consts.orderTabList" :key="index" :label="tab.label" :name="tab.name" />
      </el-tabs>

      <el-empty v-if="orderData.list.length === 0" description="暂无相关订单"></el-empty>

      <div v-else>
        <table class="tabel">
          <thead class="table_header_title">
            <tr>
              <th>商品信息</th>
              <th>属性</th>
              <th>单价</th>
              <th>折后单价</th>
              <th>数量</th>
              <th>金额</th>
              <th>折后金额</th>
              <th>订单状态</th>
              <th>操作</th>
            </tr>
          </thead>

          <tbody class="table_tbody">
            <template v-for="order in orderData.list" :key="order.orderId">
              <tr>
                <td class="noborder" colspan="9"></td>
              </tr>
              <tr>
                <td colspan="9" class="last">
                  <div class="info">
                    <div class="_left">
                      <el-checkbox v-model="order.checked" @change="(val) => onChange(val, order)"></el-checkbox>
                      <span class="order-time">{{ order.createTime }}</span>
                      <span>订单编号：{{ order.orderCode }}</span>
                    </div>
                    <div class="supplier-info">
                      <img src="@/assets/images/dianpuxiao.png" class="image" />
                      <span class="supplier-name">供应商：{{ order.supplierName }}</span>
                      <Button label="收款信息" class="pay_button" @click="onShowPayInfoClick(order)" />
                    </div>
                    <Link class="print-btn" label="打印" @click="onPrintClick(order)"></Link>
                  </div>
                </td>
              </tr>
              <tr class="goods" v-for="(goods, index) in order.orderGoodsList" :key="goods.orderGoodsId">
                <td>
                  <div class="goods-info" style="display: flex">
                    <img :src="goods.goodsImg" />
                    <span class="goods-name">{{ goods.goodsName }}</span>
                  </div>
                </td>

                <td class="goods_spec">
                  <span class="goods-spec">{{ goods.goodsSpec }}</span>
                </td>
                <td class="goods-price">
                  <span>¥{{ goods.price.toFixed(2) }}</span>
                </td>
                <td class="goods-price">
                  <span>¥{{ goods.discountPrice ? goods.discountPrice.toFixed(2) : ''}}</span>
                </td>
                <td class="last">
                  <span>{{ goods.amount }}</span>
                </td>

                <template v-if="index === 0">
                  <td class="last" :rowspan="order.orderGoodsList.length">
                    <span class="order-orderPrice">¥{{ order.orderPrice.toFixed(2) }}</span>
                  </td>
                  <td class="last" :rowspan="order.orderGoodsList.length">
                    <span class="order-orderPrice">¥{{ order.orderReceivePrice ? order.orderReceivePrice.toFixed(2) : ''}}</span>
                  </td>
                  <td class="last" :rowspan="order.orderGoodsList.length">
                    <el-tooltip v-if="goods.orderStatus === 'PAYREJECT'" popper-class="tooltip" effect="light" placement="bottom">
                      <div>
                        <span class="payReject">支付凭证未通过审核，请更换凭证</span>
                      </div>
                      <template #content>
                        <div>
                          <span>驳回备注: {{ `${order.payRefuseRemark}` }}</span>
                        </div>
                      </template>
                    </el-tooltip>
                    <el-tooltip v-else-if="goods.orderStatus === 'CANCELED'" popper-class="tooltip" effect="light" placement="bottom">
                      <div>
                        <span class="payReject">已取消</span>
                      </div>
                      <template #content>
                        <div>
                          <span>取消原因: {{ `${order.cancelReason}` }}</span>
                        </div>
                      </template>
                    </el-tooltip>

                    <span v-else>{{ consts.orderStatus[goods.orderStatus] }}</span>
                  </td>
                  <td class="last" :rowspan="order.orderGoodsList.length">
                    <div class="btns">
                      <template v-if="order.orderStatus === 'UNPAID' && order.monthlyFlag === 'YES'">
                        <Button label="月结" type="warning" class="order_button" @click="onMonthlylClick(order)" />
                      </template>

                      <template v-if="order.orderStatus === 'UNPAID' && order.afterSaleFlag !== 'COMPLETED'">
                        <Button label="上传凭证" type="warning" class="order_button" @click="onUpLoadProofClick(order, true)" />
                      </template>

                      <template v-if="order.orderStatus !== 'UNPAID'">
                        <Link v-if="order.settleType !== 'MONTHLY'" label="凭证" @click="onPreview(order)" />

                        <span v-else>月付订单</span>
                      </template>

                      <template v-if="(order.orderStatus === 'PAYAUDIT' || order.orderStatus === 'PAYREJECT') && order.afterSaleFlag === 'NOT_APPLY'">
                        <div class="proof-btn">
                          <Link label="更换" type="warning" class="change-proof" @click="onEditProofClick(order)" />
                        </div>
                      </template>

                      <template v-if="(order.orderStatus === 'UNDELIVER' || order.orderStatus === 'DELIVERED') && order.afterSaleFlag === 'NOT_APPLY'">
                        <Link label="申请售后" @click="onApplyServiceClick(order)" />
                      </template>

                      <template v-if="order.afterSaleFlag !== 'NOT_APPLY'">
                        <Link v-if="order.afterSaleFlag === 'APPLY' || order.afterSaleFlag === 'AFTERSALEING'" label="售后中" class="afterSale_button" @click="onServiceProgressClick(order)" />
                        <Link v-else-if="order.afterSaleFlag === 'COMPLETED'" label="售后完成" class="afterSale_button" @click="onServiceProgressClick(order)" />
                        <Link v-else-if="order.afterSaleFlag === 'CANCELED'" label="售后已关闭" @click="onServiceProgressClick(order)" />
                      </template>

                      <template v-if="(order.orderStatus === 'DELIVERED' || order.orderStatus === 'COMPLETED') && order.afterSaleFlag === 'NOT_APPLY'">
                        <el-tooltip popper-class="tooltip" effect="light" placement="bottom">
                          <div>
                            <Link label="物流单号" :underline="true" />
                          </div>
                          <template #content>
                            <div>
                              <span> {{ `${order.trackingNumber}` }}</span> <Button label="复制" type="warning" class="copy-btn" @click="onCopyNumberClick(order.trackingNumber)" />
                            </div>
                          </template>
                        </el-tooltip>
                      </template>

                      <template v-if="order.orderStatus === 'DELIVERED' && (order.afterSaleFlag === 'NOT_APPLY' || order.afterSaleFlag === 'COMPLETED' || order.afterSaleFlag === 'CANCELED')">
                        <Button label="确认收货" type="warning" class="order_button" @click="onConfirmClick(order)" />
                        <!-- <Button label="增加凭证" type="warning" class="order_button" @click="onUpLoadProofClick(order, true)" /> -->
                      </template>

                      <template v-if="order.orderStatus !== 'UNPAID'">
                        <Link label="订单详情" @click="onToOrderDetailClick(order)" />
                      </template>

                      <template v-if="order.orderStatus === 'CANCELED' || order.orderStatus === 'COMPLETED'">
                        <Link label="再来一单" class="order_again" @click="onAnotherOrderClick(order)" />
                      </template>

                      <template v-if="order.orderStatus === 'UNPAID' && order.afterSaleFlag !== 'COMPLETED'">
                        <Link label="取消订单" class="order_again" @click="onToDeleteOrderClick(order.orderId)" />
                      </template>
                    </div>
                  </td>
                </template>
              </tr>
              <tr>
                <td class="last" colspan="9">
                  <p class="remark">备注留言：{{ order.buyerRemark }}</p>
                </td>
              </tr>
            </template>

            <el-image-viewer v-if="showViewer" @close="closeViewer" :url-list="[url]" />
          </tbody>
        </table>

        <div class="foot">
          <div class="btn">
            <el-checkbox label="全选" v-model="orderData.checkedAll" @change="checkedAllChange"></el-checkbox>
            <Button label="批量打印" class="print-btn" :disabled="orderData.list.filter((e) => e.checked).length === 0" @click="onAllPrintClick"></Button>
          </div>

          <Pager v-if="orderData.list?.length > 0" :page="orderData.search.page" :total="orderData.total" :limit="orderData.search.limit" @current-change="onCurrentChange" />
        </div>
      </div>
    </div>
  </div>

  <Proof v-model:visible="proofVisible" :order="orderData.currOrder" @change="proofChange" />
  <Payment v-model:visible="paymentVisible" :order="orderData.currOrder" />
  <Print v-model:visible="printVisible" :list="orderData.order" />
</template>
<script setup>
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/api'
import consts from '@/consts'
import Pager from '@/components/pager/index.vue'
import Button from '@/components/button/button.vue'
import Link from '@/components/button/link.vue'
import Proof from './components/proof.vue'
import Payment from './components/payment.vue'
import Print from './components/print.vue'

const router = useRouter()

const activeName = ref('ALLORDER')

const orderData = reactive({
  total: 0,
  list: [],
  currOrder: {},
  payProof: [],
  checkedAll: false,
  search: {
    page: 1,
    limit: consts.Limit,
    orderStatus: ''
  },
  order: []
})

const showViewer = ref(false)
const proofVisible = ref(false)
const printVisible = ref(false)
const paymentVisible = ref(false)
const url = ref('')

const onPreview = (order) => {
  url.value = order.payProof
  showViewer.value = true
}
// 关闭查看器
const closeViewer = () => {
  showViewer.value = false
}

const monthlyPay = async (order) => {
  let { err } = await api.post(`/medinstrument/site/order/monthlyPay?orderId=${order.orderId}`)
  if (err) {
    ElMessage.error(err)
  } else {
    loadData()
  }
}

const confirmOrder = async (item) => {
  let { err } = await api.post(`/medinstrument/site/order/confirmReceipt?orderId=${item.orderId}`)
  if (err) {
    ElMessage.error(err)
  } else {
    loadData()
  }
}

const serviceSubmit = async (goods, item) => {
  let subBackGoodsVos = goods.map((e) => {
    return {
      amount: e.amount,
      backGoodsPrice: e.sum,
      goodsSpecId: e.goodsSpecId,
      goodsSpec: e.goodsSpec,
      orderGoodsId: e.orderGoodsId,
      totalPrice: e.totalPrice,
      unit: e.unit,
      goodsName: e.goodsName
    }
  })
  let params = {
    backPrice: item.backPrice,
    backRemark: item.backRemark,
    orderCode: orderData.currOrder.orderCode,
    orderId: orderData.currOrder.orderId,
    supplierId: orderData.currOrder.supplierId,
    supplierName: orderData.currOrder.supplierName,
    subBackGoodsVos: subBackGoodsVos
  }
  let { err } = await api.post(`/medinstrument/site/back/submitBack`, params)
  if (err) {
    ElMessage.error(err)
  } else {
    loadData()
  }
}

const uploadProof = async (payProof) => {
  let url = `/medinstrument/site/order/uploadPaymentVoucher?orderId=${orderData.currOrder.orderId}&payProof=${payProof}`
  if (orderData.currOrder.payProof) {
    url = `/medinstrument/site/order/updatePaymentVoucher?orderId=${orderData.currOrder.orderId}&payProof=${payProof}`
  }
  let { err } = await api.post(url)
  if (err) {
    ElMessage.error(err)
  } else {
    ElMessage.success('上传凭证成功')
    loadData()
  }
}

const anotherOrder = async (orderId) => {
  let { err } = await api.post(`/medinstrument/site/cart/addAgain?orderId=${orderId}`)
  if (err) {
    ElMessage.error(err)
  } else {
    router.push('/shoppingCart')
  }
}

const delOrder = async (orderId) => {
  let { err } = await api.post(`/medinstrument/site/order/cancelOrder?orderId=${orderId}&remark=''`)
  if (err) {
    ElMessage.error(err)
  } else {
    loadData()
  }
}

const loadData = async () => {
  let status = orderData.search.orderStatus
  let url = `/medinstrument/site/order/getOrderList?orderStatus=${status}`
  if (status === 'afterSaleFlag') {
    url = `/medinstrument/site/order/getOrderList?backOrderFlag=YES`
  }

  let { data, err } = await api.get(url, { limit: orderData.search.limit, page: orderData.search.page })
  if (err) {
    ElMessage.error(err)
  } else {
    orderData.list = data.list
    orderData.total = data.count

    orderData.list.forEach((e) => {
      e.orderGoodsList.map((item) => {
        item.orderStatus = e.orderStatus
        item.payProof = e.payProof
      })
    })
  }
}

const onGoodsClick = (goodsId) => {
  let { href } = router.resolve({
    path: `/goods/${goodsId}`
  })
  window.open(href, '_blank')
}

const onToOrderDetailClick = (order) => {
  router.push({
    path: `/orderDetail/${order.orderId}`
  })
}

const onToDeleteOrderClick = (orderId) => {
  ElMessageBox.confirm('是否确认取消当前订单', '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      delOrder(orderId)
    })
    .catch(() => {})
}

const onAnotherOrderClick = (item) => {
  anotherOrder(item.orderId)
}

const onTabClick = (tab) => {
  orderData.search.orderStatus = tab.props.name === 'ALLORDER' ? '' : tab.props.name
  loadData()
}

const onCurrentChange = (val) => {
  orderData.search.page = val
  loadData()
}

const onEditProofClick = (item) => {
  orderData.currOrder = Object.assign({}, item)
  proofVisible.value = true
}

const onUpLoadProofClick = (order, isNew = false) => {
  orderData.currOrder = Object.assign({}, order, { isNew })
  proofVisible.value = true
}

const onMonthlylClick = (order) => {
  ElMessageBox.confirm(`是否确认选择月付`, '系统', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    cancelButtonClass: 'cancelButtonClass',
    confirmButtonClass: 'confirmButtonClass',
    showClose: false,
    closeOnClickModal: false,
    closeOnPressEscape: false
  })
    .then(() => {
      monthlyPay(order)
    })
    .catch(() => {})
}

const proofChange = (payProof) => {
  uploadProof(payProof)
}

const checkedAllChange = (val) => {
  orderData.list.forEach((e) => {
    e.checked = val
  })
}

const onChange = (val, row) => {
  row.checked = val
  let selected = []
  // 遍历checkbox，子复选框有一个未选中时，全选框设为false不选状态
  for (var i = 0; i < orderData.list.length; i++) {
    if (orderData.list[i].checked) {
      selected.push(row)
    }
  }

  orderData.checkedAll = orderData.list.length === selected.length
}

const onPrintClick = (item) => {
  orderData.order = [item]
  printVisible.value = true
}

const onAllPrintClick = () => {
  orderData.order = orderData.list.filter((e) => e.checked)
  printVisible.value = true
}

const onApplyServiceClick = (order) => {
  router.push({ path: '/AfterSale', query: { orderId: order.orderId } })
}

const onServiceChange = (goods, item) => {
  serviceSubmit(goods, item)
}

const onServiceProgressClick = (order) => {
  router.push({ path: '/AfterSale', query: { type: order.afterSaleFlag, orderId: order.orderId } })
}

const onShowPayInfoClick = (item) => {
  orderData.currOrder = Object.assign({}, item)
  paymentVisible.value = true
}

const onConfirmClick = (item) => {
  ElMessageBox.confirm(`是否确认收货`, '系统', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    cancelButtonClass: 'cancelButtonClass',
    confirmButtonClass: 'confirmButtonClass',
    showClose: false,
    closeOnClickModal: false,
    closeOnPressEscape: false
  })
    .then(() => {
      confirmOrder(item)
    })
    .catch(() => {})
}

const onCopyNumberClick = (row) => {
  _copy(row)
}

const _copy = (context) => {
  navigator.clipboard
    .writeText(context)
    .then(() => {
      ElMessage.success('复制成功')
    })
    .catch(() => {
      ElMessage.error('复制失败')
    })
}

onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.order {
  min-height: 393px;

  .order-content {
    width: 1080px;
    margin: 10px auto;

    .tabel {
      border-collapse: collapse;
      width: 100%;

      th {
        width: 160px;
      }
      .table_header_title {
        color: var(--span-color-text);
        background: var(--color-background);
        height: 42px;
      }

      .table_tbody {
        tr {
          td {
            text-align: center;
            line-height: 18px;
            border-bottom: 1px solid var(--border-color);
          }

          td:first-child {
            border-left: 1px solid var(--border-color);
          }

          td.last {
            border-right: 1px solid var(--border-color);

            .btns {
              display: flex;
              align-items: center;
              justify-content: center;
              flex-direction: column;

              .el-button {
                margin-left: 0;
              }

              span {
                margin-bottom: 6px;
              }

              .proof-btn {
                display: flex;
                line-height: 18px;
                font-weight: 500;
                color: var(--color-text);

                .change-proof {
                  color: var(--color-primary);
                  font-size: 12px;
                  line-height: 16px;
                  margin-left: 8px;
                }
              }

              .afterSale_button {
                color: var(--color-primary);
              }
            }

            .btns:first-child {
              margin-top: 6px;
            }
          }

          .remark {
            text-align: left;
            padding: 12px 0 12px 20px;
            font-size: 12px;
            line-height: 16px;
          }

          .order_button {
            width: 76px;
            height: 30px;
            border-radius: 4px;
            margin-bottom: 6px;
          }

          .order_again {
            color: var(--color-text);
            font-weight: 500;
          }
        }

        td.noborder {
          border: 0 !important;
          height: 25px;
        }

        .info {
          display: flex;
          justify-content: space-between;
          align-items: center;
          background: #fff9ee;
          line-height: 18px;
          height: 42px;
          padding: 12px 20px 12px 10px;
          box-sizing: border-box;
          border-top: 1px solid var(--border-color);

          ._left {
            display: flex;
            align-items: center;

            td {
              border-bottom: 1px solid var(--border-color);
            }

            .order-time {
              margin: 0 12px;
            }
          }

          .supplier-info {
            display: flex;
            align-items: center;

            .supplier-name {
              margin: 0 20px 0 10px;
            }

            .pay_button {
              width: 58px;
              height: 24px;
              border: 1px solid rgba(62, 66, 76, 1);
              border-radius: 4px;
              background-color: #fff;
              color: var(--color-text);
              font-size: 12px;
              line-height: 16px;
            }
          }

          .print-btn {
            font-size: 12px;
          }
        }

        .goods {
          .goods-info {
            display: flex;
            align-items: center;
            padding: 20px 20px 20px 54px;

            img {
              width: 72px;
              height: 72px;
            }
          }

          .goods-name {
            width: 180px;
            margin-left: 12px;
          }

          .order-orderPrice {
            color: var(--color-primary);
          }

          .payReject {
            position: relative;
          }

          .payReject::after {
            content: '';
            position: absolute;
            left: 0;
            right: 0;
            bottom: -6px;
            width: 100%;
            height: 1px;
            background-color: var(--color-text);
          }
        }
      }
    }

    .foot {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 30px 0;

      .btn {
        display: flex;
        align-items: center;

        .print-btn {
          width: 68px;
          height: 28px;
          background: #ffffff;
          border: 1px solid var(--border-color);
          line-height: 16px;
          margin-left: 8px;
        }

        .print-btn:hover {
          color: var(--span-color-text);
        }
      }
    }
  }
}
</style>

<style>
.tooltip {
  padding: 15px 12px !important;
  line-height: 18px;
  box-shadow: 1px 1px 10px 3px #d3d3d6;
  font-size: 14px !important;
  color: var(--span-color-text) !important;
}

.copy-btn {
  width: 38px;
  height: 24px;
  border-radius: 4px;
  margin-left: 15px;
}
</style>
